import React, {useEffect} from "react";
import { Form, Input } from "antd";

import prompt from "vendor/utils/prompt";
import { WrappedComponentProps } from 'vendor/components/pro-hoc/withModal';

import { initAdminOfAccount } from '../../../api';

interface InitAdminProps extends WrappedComponentProps{
    accountId: string;
}

const InitAdmin: React.FC<InitAdminProps> = (props) => {
    const { form } = useInitAdmin(props);

    return <Form
        form={form}
        labelCol={{span: 5}}
        wrapperCol={{span: 15}}
    >
        <Form.Item
            label="用户名"
            name="userName"
            rules={[{required: true, message: "请填写用户名!"}]}
        >
            <Input />
        </Form.Item>
        <Form.Item
            label="昵称"
            name="nickName"
            rules={[{required: true, message: "请填写昵称!"}]}
        >
            <Input />
        </Form.Item>
        <Form.Item
            label="密码"
            name="password"
            rules={[{required: true, message: "请填写密码!"}]}
        >
            <Input />
        </Form.Item>
        <Form.Item
            label="邮箱"
            name="email"
            rules={[
                {required: true, message: "请填写邮箱!"},
                {type: "email", message: "请填写正确的邮箱!"},
            ]}
        >
            <Input />
        </Form.Item>
        <Form.Item
            label="手机号"
            name="phonenumber"
            rules={[
                {required: true, message: "请填写手机号!"},
                {pattern: /^1[3456789]\d{9}$/, message: "请填写正确的手机号!"},
            ]}
        >
            <Input />
        </Form.Item>
    </Form>
}

export default InitAdmin;

const useInitAdmin = (props: InitAdminProps) => {
    const { modalControl, accountId } = props;
    const [ form ] = Form.useForm();

    useEffect(() => {
        modalControl.registerOk(handleSubmit)
    })

    const handleSubmit = () => {
        form.validateFields().then((values) => {
            initAdminOfAccount(accountId, values).then(() =>{
                prompt.success("初始化成功!");
                modalControl.close();
            }).catch(() => modalControl.hideSaving());
        }).catch(() => modalControl.hideSaving());
    }

    return { form }
}